
package com.idealighter.game.games.wknh.handler;

import com.google.inject.Inject;

import com.idealighter.game.core.annotation.ResMsgHandler;
import com.idealighter.game.dictionary.dic.WknhBatteryDic;
import com.idealighter.game.dictionary.domain.WknhBatteryDomain;
import com.idealighter.game.games.wknh.WknhPlayer;
import com.idealighter.game.games.wknh.dto.BatteryInfo;
import com.idealighter.game.games.wknh.message.ReqSwitchBatteryMsg;
import com.idealighter.game.games.wknh.message.ResFireMsg;
import com.idealighter.game.message.core.ResMessage;
import com.idealighter.game.robot.core.Player;
import com.idealighter.game.robot.handler.ResMessageHandler;
import com.idealighter.utils.code.RandCodeUtil;

import java.util.concurrent.TimeUnit;


@ResMsgHandler(523231)
public class ResFireHandler implements ResMessageHandler {

  // private static final Logger LOG = LoggerFactory.getLogger(ResFireHandler.class);
  @Inject
  private WknhBatteryDic batteryDic;

  @Override
  public void action(Player player, ResMessage message) {
    ResFireMsg msg = (ResFireMsg) message;

    if (msg.getPlayerId() == player.playerId && RandCodeUtil.random(100) < 1) { // 每100炮有一次换炮概率
      WknhPlayer wknhPlayer = (WknhPlayer) player;
      BatteryInfo oldBattery = wknhPlayer.battery;
      int oldBatteryId = getBatteryId(oldBattery.getScore());
      // 新炮
      WknhBatteryDomain newBatteryDom = RandCodeUtil.randomList(batteryDic.list());

      // 间隔
      int gap = newBatteryDom.getId() - oldBatteryId;
      for (int i = 0; i < Math.abs(gap); i++) {
        wknhPlayer.schedule(() -> {
          ReqSwitchBatteryMsg reqMsg = new ReqSwitchBatteryMsg();
          reqMsg.setType(gap > 0 ? 0 : 1);
          player.sendMsg(reqMsg);
        }, 1, TimeUnit.SECONDS);
      }
    }
  }

  private int getBatteryId(int score) {
    for (WknhBatteryDomain batteryDom : batteryDic.list()) {
      if (batteryDom.getScore() == score) {
        return batteryDom.getId();
      }
    }

    return 0;
  }
}
